﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using OBUCare.Core.Models;
using OBUCare.Core.DataAccess;
using OBUCare.Core.Common;
using System.Data.Entity.Validation;
using System.Transactions;
using System.Data.Common;

namespace OBUCare.Core.BL
{

    public class OBUCareOrderMgr : IDisposable
    {
        private OBU_CAREContext obuDB = new OBU_CAREContext();
        private ISSUE_RPTContext rptDB = new ISSUE_RPTContext();
        private ConfigMgr configMgr = new ConfigMgr();


        public string GetVehicelClass(short vehicelclass)
        {
            string vclass = string.Empty;
            switch (vehicelclass)
            {
                case 1: vclass = "A";
                    break;
                case 2: vclass = "B";
                    break;
                case 3: vclass = "C";
                    break;
                case 4: vclass = "D";
                    break;
                case 5: vclass = "E";
                    break;
            }
            return vclass;
        }


        /// <summary>
        /// 录入维修单，如果收了备签的押金，则生成交易日志，并返回交易日志，否则返回NULL
        /// </summary>
        /// <param name="repair_orders"></param>
        /// <param name="u"></param>
        /// <returns></returns>
        public bool NewRepariOrder(REPAIR_ORDERS repair_orders, IList<REPAIR_ORDER_FAULT> faults, OPERATOR u, string AgentNo, string ip, bool isNormalRepair, decimal? oneRepairPay, decimal? oneRepairPaySup)
        {
            bool result = false;
            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    repair_orders.CREATED_BY = u.OPERATOR_NO;
                    repair_orders.CREATED_DATE = DateTime.Now;
                    repair_orders.MODIFY_BY = u.OPERATOR_NO;
                    repair_orders.MODIFY_DATE = DateTime.Now;
                    string client_ip = string.Empty;
                    if (AgentNo == "")//不是补录的情况，直接获取登录人员的ip
                    {
                        client_ip = u.CLIENT_IP;
                        AgentNo = u.AgentNo;
                    }
                    else
                    {
                        client_ip = ip;
                    }
                    repair_orders.CLIENT_IP = client_ip;
                    repair_orders.AGENT_NO = AgentNo;
                    repair_orders.CURRENT_HANDLER = u.OPERATOR_NO;

                    repair_orders.REPAIR_ORDER_NO = this.GetRepairOrderNO(repair_orders.AGENT_NO);
                    //区分去一口价维修和普通维修的状态
                    repair_orders.STATUS = isNormalRepair ? RepairOrderStatus.ReadyForReturnToRepairGroup.ToInt().Value : RepairOrderStatus.OneRepair.ToInt().Value; //将状态设置为待返维修组
                    repair_orders.DISPOSE_TYPE = DisposeType.Repair.ToInt().Value;
                    repair_orders.CONFIRM_REPAIRED = isNormalRepair ? ConfirmRepairedStatus.WaitingForConfirm.ToInt().Value : ConfirmRepairedStatus.Repair.ToInt().Value;

                    obuDB.REPAIR_ORDERS.Add(repair_orders);
                    obuDB.SaveChanges();

                    if (isNormalRepair)
                    {
                        //添加故障描述
                        faults.Each(f =>
                        {
                            f.REPAIR_ORDER_ID = repair_orders.ID;
                            obuDB.REPAIR_ORDER_FAULT.Add(f);
                        });

                        OPERATION_CARE_LOGS log = null;
                        //如果收取的备用标签的押金，则生成交易日志
                        if (repair_orders.SPARE_OBU_PRICE > 0)
                        {
                            string remark = "收取备用标签押金:" + repair_orders.SPARE_OBU_PRICE.ToText();
                            log = LogtransactionLog(u, TransactionType.CollectsDeposit, repair_orders.ID, repair_orders.OBU_NO, repair_orders.SPARE_OBU_PRICE, repair_orders.USER_NO, remark);
                        }
                    }
                    else
                    {
                        OPERATION_CARE_LOGS log = null;
                        string remark = oneRepairPaySup + "";
                        log = LogtransactionLog(u, TransactionType.OneRepair, repair_orders.ID, repair_orders.OBU_NO, oneRepairPay, repair_orders.USER_NO, remark);
                    }
                    ////修改标签状态变化 主要还是增加进度信息
                    changRepariOrderStatus(repair_orders.ID, isNormalRepair ? RepairOrderStatus.ReadyForReturnToRepairGroup : RepairOrderStatus.OneRepair, u);

                    obuDB.SaveChanges();
                    scope.Complete();
                    result = true;
                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }

            return result;
        }

        /// <summary>
        /// 录入维修单，如果收了备签的押金，则生成交易日志，并返回交易日志，否则返回NULL
        /// </summary>
        /// <param name="repair_orders"></param>
        /// <param name="u"></param>
        /// <returns></returns>
        public bool AlterRepariOrder(REPAIR_ORDERS repair_orders, IList<REPAIR_ORDER_FAULT> faults, OPERATOR u, string AgentNo, string ip)
        {
            bool result = false;
            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    var old_repair_orders = obuDB.REPAIR_ORDERS.ToList().Where(m => m.ID == repair_orders.ID).OrderBy(m => m.ID).FirstOrDefault();

                    #region 是否需要备签不可编辑 则不会影响到日志信息
                    OPERATION_CARE_LOGS log = null;

                    ////如果更新前  旧维修单信息没有押金信息 编辑新增押金信息则入系统
                    //if ((old_repair_orders.SPARE_OBU_PRICE <= 0 || old_repair_orders.SPARE_OBU_PRICE == null) && repair_orders.SPARE_OBU_PRICE > 0)
                    //{
                    //    string remark = "收取备用标签押金:" + repair_orders.SPARE_OBU_PRICE.ToText();
                    //    log = LogtransactionLog(u, TransactionType.CollectsDeposit, repair_orders.ID, repair_orders.OBU_NO, repair_orders.SPARE_OBU_PRICE, repair_orders.USER_NO, remark);
                    //}
                    //else if (old_repair_orders.SPARE_OBU_PRICE != repair_orders.SPARE_OBU_PRICE)//如果编辑时 填写的押金与录入维修单时填写的押金不一致 则修改收取押金日志的金额
                    //{
                    //    var operationCareLogs = (from i in obuDB.OPERATION_CARE_LOGS.ToList()
                    //                             where i.OPERATION_ID == old_repair_orders.ID && i.OPERATION_KIND == TransactionType.CollectsDeposit.ToInt()
                    //                             select i).FirstOrDefault();
                    //    if (operationCareLogs != null)
                    //        operationCareLogs.AMOUNT = repair_orders.SPARE_OBU_PRICE;
                    //    obuDB.SaveChanges();
                    //}
                    #endregion

                    old_repair_orders.MODIFY_BY = u.OPERATOR_NO;
                    old_repair_orders.MODIFY_DATE = DateTime.Now;
                    //string client_ip = string.Empty;
                    //if (AgentNo == "")
                    //{
                    //    client_ip = u.CLIENT_IP;
                    //    AgentNo = u.AgentNo;
                    //}
                    //else
                    //{
                    //    client_ip = ip;
                    //}
                    //old_repair_orders.AGENT_NO = AgentNo;
                    //old_repair_orders.CLIENT_IP = client_ip; (编辑的时候不用更新受理营业厅)

                    old_repair_orders.CURRENT_HANDLER = u.OPERATOR_NO;


                    old_repair_orders.DISPOSE_TYPE = DisposeType.Repair.ToInt().Value;
                    old_repair_orders.FACE_STATUS = repair_orders.FACE_STATUS;
                    old_repair_orders.MAX_PRICE = repair_orders.MAX_PRICE;
                    old_repair_orders.MOBILE_TEL_NO = repair_orders.MOBILE_TEL_NO;
                    old_repair_orders.OWNER_NAME = repair_orders.OWNER_NAME;
                    old_repair_orders.REGISTER_DATE = repair_orders.REGISTER_DATE;
                    old_repair_orders.REPAIR_TYPE = repair_orders.REPAIR_TYPE;
                    old_repair_orders.REPORT_DATE = repair_orders.REPORT_DATE;
                    old_repair_orders.SUPPLIER = repair_orders.SUPPLIER;
                    old_repair_orders.SPEC_NAME = repair_orders.SPEC_NAME;
                    old_repair_orders.SUPPLIER_ID = repair_orders.SUPPLIER_ID;
                    old_repair_orders.SPEC_ID = repair_orders.SPEC_ID;
                    old_repair_orders.OBU_NO = repair_orders.OBU_NO;
                    old_repair_orders.VEHICLE_CLASS = repair_orders.VEHICLE_CLASS;
                    old_repair_orders.VEHICLE_PLATE_NO = repair_orders.VEHICLE_PLATE_NO;
                    old_repair_orders.USER_NO = repair_orders.USER_NO;
                    old_repair_orders.TEL_NO = repair_orders.TEL_NO;
                    old_repair_orders.REPORTER = repair_orders.REPORTER;
                    old_repair_orders.SPARE_OBU_ISSUE_DATE = repair_orders.SPARE_OBU_ISSUE_DATE;
                    old_repair_orders.SPARE_OBU_NO = repair_orders.SPARE_OBU_NO;
                    //old_repair_orders.SPARE_OBU_PRICE = repair_orders.SPARE_OBU_PRICE; //是否需要备签不可编辑 押金不可编辑
                    old_repair_orders.REPAIRED_COMMENT = repair_orders.REPAIRED_COMMENT;

                    obuDB.SaveChanges();

                    var old_faults = obuDB.REPAIR_ORDER_FAULT.FindAll(m => m.REPAIR_ORDER_ID == repair_orders.ID);
                    old_faults.Each(m => obuDB.REPAIR_ORDER_FAULT.Remove(m));
                    //添加故障描述
                    faults.Each(f =>
                    {

                        f.REPAIR_ORDER_ID = repair_orders.ID;
                        obuDB.REPAIR_ORDER_FAULT.Add(f);
                    });
                    obuDB.SaveChanges();
                    scope.Complete();
                    result = true;
                }
                catch (Exception ex)
                {
                    var msg = ex.Message;
                }

            }

            return result;
        }


        /// <summary>
        /// 发生涉及金钱的交易时，生成交易日志
        /// </summary>
        /// <param name="u"></param>
        /// <param name="transactionType"></param>
        /// <param name="OPERATION_ID"></param>
        /// <param name="obuNo"></param>
        /// <param name="AMOUNT"></param>
        /// <param name="user_no"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        private OPERATION_CARE_LOGS LogtransactionLog(OPERATOR u, TransactionType transactionType, long OPERATION_ID, string obuNo, decimal? AMOUNT, string user_no, string remark)
        {
            OPERATION_CARE_LOGS log = new OPERATION_CARE_LOGS();
            log.AMOUNT = AMOUNT;
            log.CLIENT_IP = u.CLIENT_IP;
            log.OBU_NO = obuNo;
            log.OPERATION_ID = OPERATION_ID;
            log.OPERATION_KIND = transactionType.ToInt().Value;
            log.OPERATOR_NO = u.OPERATOR_NO;
            log.POS_ID = u.PosID;
            log.RECORD_TIME = DateTime.Now;
            log.REMARK = remark;
            log.USER_NO = user_no.Trim();
            obuDB.OPERATION_CARE_LOGS.Add(log);
            //obuDB.SaveChanges();
            return log;
        }
        /// <summary>
        /// 领取标签时生成服务费
        /// </summary>
        /// <param name="orderID">维修单ID</param>
        /// <param name="adjustType">费用类别</param>
        /// <param name="Amount">金额</param>
        /// <param name="remark">备注：逾期天数*单价</param>
        /// <param name="u">操作员</param>
        /// <returns></returns>
        private REPAIR_ORDER_ADJUST ServerFeeLog(REPAIR_ORDERS repairOrder, int adjustType, decimal Amount, string remark, OPERATOR u)
        {
            REPAIR_ORDER_ADJUST orderAdjust = new REPAIR_ORDER_ADJUST();
            orderAdjust.REPAIR_ORDER_ID = repairOrder.ID;
            orderAdjust.REPAIR_ORDERS = repairOrder;
            orderAdjust.ADJUST_TYPE = adjustType;
            orderAdjust.AMOUNT = Amount;
            orderAdjust.CREATED_BY = u.OPERATOR_NO;
            orderAdjust.CREATED_DATE = DateTime.Now;
            orderAdjust.MODIFY_BY = u.OPERATOR_NO;
            orderAdjust.MODIFY_DATE = DateTime.Now;
            orderAdjust.COMMENT = remark;
            obuDB.REPAIR_ORDER_ADJUST.Add(orderAdjust);
            return orderAdjust;
        }

        /// <summary>
        /// 是导入过报价信息
        /// </summary>
        /// <param name="repairOrderID"></param>
        /// <returns></returns>
        public bool ImportBefore(long repairOrderID)
        {
            return obuDB.REPAIR_ORDER_PRICE.Count(r => r.REPAIR_ORDER_ID == repairOrderID) > 0;
        }

        /// <summary>
        /// 导入厂商报价
        /// </summary>
        /// <param name="priceList"></param>
        /// <returns></returns>
        public bool ImportRepairOrderPrice(IList<REPAIR_ORDER_PRICE> priceList, OPERATOR u)
        {

            TraceHelper.TraceInfo("开始导入厂商报价");

            bool result = false;
            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    var repairOrders = (from r in priceList
                                        select new { ID = r.REPAIR_ORDER_ID, DisposeType = r.getDisposeType() }).Distinct();

                    var ids = repairOrders.ConcatToString(o => o.ID.ToString(), ",");



                    //删除先前导入的数据,并恢复维修单中的厂商处理意见(处置方式)
                    if (!ids.IsNullOrEmpty())
                    {
                        TraceHelper.TraceInfo("删除先前导入的数据,编号：{0}", ids);

                        string sql = string.Format("DELETE FROM [REPAIR_ORDER_PRICE] where REPAIR_ORDER_ID in ({0})", ids);
                        obuDB.Database.ExecuteSqlCommand(sql);

                        sql = string.Format("UPDATE [REPAIR_ORDERS] SET [DISPOSE_TYPE] ={0}  WHERE ID in ({1})", DisposeType.Repair.ToInt(), ids);
                        obuDB.Database.ExecuteSqlCommand(sql);
                    }

                    //修改维修单状态,及处置方式
                    repairOrders.Each(item =>
                    {
                        var o = obuDB.REPAIR_ORDERS.Find(item.ID);
                        o.DISPOSE_TYPE = item.DisposeType.ToInt().Value;
                        changRepariOrderStatus(o, o.STATUS != RepairOrderStatus.OneRepair.ToInt().Value ? RepairOrderStatus.SupplierReturnedRepariPrice : RepairOrderStatus.OneRepair, u);
                    });
                    //添加报价信息到数据库
                    // priceList.Each(p => obuDB.REPAIR_ORDER_PRICE.Add(p));
                    priceList.Each(items =>
                    {
                        int i = int.Parse(obuDB.REPAIR_ORDER_PRICE.Where(p => p.OBU_NO == items.OBU_NO).Count().ToString());
                        while (i-- > 0)
                        {
                            var item = obuDB.REPAIR_ORDER_PRICE.Where(p => p.OBU_NO == items.OBU_NO).FirstOrDefault();
                            obuDB.REPAIR_ORDER_PRICE.Remove(item);//删除标签重复项
                            obuDB.SaveChanges();
                        }
                        obuDB.REPAIR_ORDER_PRICE.Add(items);
                    });
                    obuDB.SaveChanges();
                    scope.Complete();
                    result = true;
                }
                catch (Exception ex)
                {
                    TraceHelper.TraceError("导入厂商报价出错：", ex);
                    throw ex;
                }
            }


            TraceHelper.TraceInfo("导入厂商报价结束");
            return result;
        }

        /// <summary>
        /// 调整费用
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public bool AdjustRepariOrderFee(IList<REPAIR_ORDER_ADJUST> list)
        {
            list.Each(a =>
            {
                //a.ADJUST_TYPE = a.ADJUST_TYPE;
                obuDB.REPAIR_ORDER_ADJUST.Add(a);
            });
            obuDB.SaveChanges();
            return true;
        }


        /// <summary>
        /// 交接维修单
        /// </summary>
        /// <param name="info">交接单的基本信息</param>
        /// <param name="details">交接的维修单号及其对应的备注</param>
        /// <param name="u">当前操作员</param>
        /// <returns>返回交接单号</returns>
        public long? Transfer(TRANSFER_BILLS info, Dictionary<long, string> details, OPERATOR u)
        {
            long? newID = null;

            TransactionOptions s = new TransactionOptions();
            s.Timeout = new TimeSpan(0, 10, 0);
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew, s))
            {
                try
                {
                    info.CREATED_BY = u.OPERATOR_NO;
                    info.CREATED_DATE = DateTime.Now;
                    info.MODIFY_BY = u.OPERATOR_NO;
                    info.MODIFY_DATE = DateTime.Now;



                    TransferType transferType = (TransferType)info.TRANSFER_TYPE.Value;

                    //数据库中存的枚举对应的ID
                    info.TRANSFER_TYPE = transferType.ToInt().Value;

                    if (transferType == TransferType.RepairCenterToSupplier)
                        info.STATUS = TransferStatus.Confirmed.ToInt().Value;
                    else
                        info.STATUS = TransferStatus.Normal.ToInt().Value;

                    info.TRANSFER_BILL_NO = this.GetTransferOrderNO(transferType);

                    //维修单的状态
                    RepairOrderStatus repairOrderStatus = RepairOrderStatus.ReturnedToRepairGroup;

                    //获取厂商编号
                    long oID = details.First().Key;
                    var order = (from o in obuDB.View_RepariOrders.ToList()
                                 where o.ID == oID
                                 select o).FirstOrDefault();
                    // View_RepariOrders order = obuDB.View_RepariOrders.Find(oID);
                    string supplier = order.SUPPLIERS_ID.ToString();
                    string agent = order.AGENT_NO;

                    switch (transferType)
                    {
                        case TransferType.AgentToRepairCenter:
                            info.TRANSFER_FROM = u.AgentNo;
                            info.TRANSFER_TO = ConfigMgr.RepairGroupNo;

                            //将维修单的状态修改为已经退回维修组
                            repairOrderStatus = RepairOrderStatus.ReturnedToRepairGroup;
                            break;

                        case TransferType.RepairCenterToSupplier:
                            info.TRANSFER_FROM = ConfigMgr.RepairGroupNo;
                            info.TRANSFER_TO = supplier;

                            //将维修单的状态修改为已经返回厂商
                            repairOrderStatus = RepairOrderStatus.ReturnedToSupplier;
                            break;
                        case TransferType.SupplierToRepairCenter:
                            info.TRANSFER_FROM = supplier;
                            info.TRANSFER_TO = ConfigMgr.RepairGroupNo;

                            //将维修单的状态修改为已经维修并返回维修组
                            repairOrderStatus = RepairOrderStatus.RepairedAndReturnedToRepariGroup;
                            break;
                        case TransferType.RepairCenterToAgent:
                            info.TRANSFER_FROM = ConfigMgr.RepairGroupNo;
                            info.TRANSFER_TO = agent;

                            //将维修单的状态修改为已经维修并返回营业厅,但未被营业厅确认
                            repairOrderStatus = RepairOrderStatus.RepairedAndReturnedToAgent;
                            break;
                    }

                    //var trx= obuDB.Database.Connection.BeginTransaction();
                    obuDB.TRANSFER_BILLS.Add(info);
                    obuDB.SaveChanges();
                    long tbID = info.ID;
                    details.Each(kv =>
                    {
                        var det = new TRANSFER_BILL_DETAIL();
                        det.REPAIR_ORDER_ID = kv.Key;
                        det.TRANSAFER_BILL_ID = tbID;
                        det.REMARK = kv.Value;
                        obuDB.TRANSFER_BILL_DETAIL.Add(det);

                        changRepariOrderStatus(kv.Key, repairOrderStatus, u);
                    });

                    obuDB.SaveChanges();
                    newID = info.ID;
                    scope.Complete();
                }
                catch (Exception ex)
                {
                    var msg = ex.Message;
                    throw ex;
                }
            }
            return newID;
        }



        /// <summary>
        /// 确认接收，仅交接方向为营业厅->维修组 或 维修组->营业厅 时，需要确认
        /// </summary>
        /// <param name="id"></param>
        /// <param name="u"></param>
        /// <returns></returns>
        public bool ConfirmReceived(long id, OPERATOR u)
        {
            var bill = this.obuDB.TRANSFER_BILLS.Find(id);
            RepairOrderStatus repairStatus = RepairOrderStatus.ReadyForReturnToSupplier;

            //交接方向
            TransferType transferType = (TransferType)bill.TRANSFER_TYPE.Value;
            //仅这两种交接方向时，才需要确认
            if (transferType == TransferType.AgentToRepairCenter || transferType == TransferType.RepairCenterToAgent)
            {
                if (transferType == TransferType.RepairCenterToAgent)
                {
                    repairStatus = RepairOrderStatus.ReadyForInformCustomer;
                }

                bill.STATUS = TransferStatus.Confirmed.ToInt().Value;
                bill.CONFIRM_DATE = DateTime.Now;
                bill.MODIFY_BY = u.OPERATOR_NO;
                bill.MODIFY_DATE = DateTime.Now;
                //obuDB.SaveChanges();


                var details = from d in obuDB.TRANSFER_BILL_DETAIL
                              where d.TRANSAFER_BILL_ID == bill.ID
                              select d;
                details.Each(d =>
                    {
                        changRepariOrderStatus(d.REPAIR_ORDER_ID, repairStatus, u);
                    });

                obuDB.SaveChanges();
            }

            return true;
        }

        /// <summary>
        /// 确认是否维修
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="repair"></param>
        /// <param name="u"></param>
        /// <returns></returns>
        public bool ConfirmWhetherToRepair(IEnumerable<long> ids, ConfirmRepairedStatus repair, OPERATOR u)
        {
            ids.Each(id =>
                {
                    var order = obuDB.REPAIR_ORDERS.Find(id);
                    if (order != null)
                    {
                        order.CONFIRM_REPAIRED = repair.ToInt().Value;
                        RepairOrderStatus status = RepairOrderStatus.ConfirmedWithRepairByCustomer;
                        //if (repair == ConfirmRepairedStatus.NotRepair)
                        //    status = RepairOrderStatus.ConfirmedWithoutRepairByCustomer;
                        changRepariOrderStatus(order, status, u);
                    }
                });
            obuDB.SaveChanges();
            return true;
        }

        /// <summary>
        /// 通知厂商维修
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="u"></param>
        /// <returns></returns>
        public bool InformeSupplierToRepair(IEnumerable<long> ids, OPERATOR u)
        {
            ids.Each(id =>
                {
                    var order = obuDB.REPAIR_ORDERS.Find(id);
                    if (order != null)
                    {
                        RepairOrderStatus status = RepairOrderStatus.InformeSupplierToRepair;
                        changRepariOrderStatus(order, status, u);
                    }
                });
            obuDB.SaveChanges();
            return true;
        }

        /// <summary>
        /// 通知客户领取标签
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="u"></param>
        /// <returns></returns>
        public bool InformeCustomerToGetBack(IEnumerable<long> ids, OPERATOR u)
        {
            ids.Each(id =>
                {
                    var order = obuDB.REPAIR_ORDERS.Find(id);
                    if (order != null)
                    {
                        RepairOrderStatus status = RepairOrderStatus.InformedCustomer;
                        changRepariOrderStatus(order, status, u);
                    }
                });
            obuDB.SaveChanges();
            return true;
        }

        /// <summary>
        /// 未联系上客户领取标签
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="u"></param>
        /// <returns></returns>
        public IList<REPAIR_ORDERS> InformeWithoutCustomerToGetBack(IEnumerable<long> ids, OPERATOR u)
        {
            IList<REPAIR_ORDERS> Ilist = new List<REPAIR_ORDERS>();
            ids.Each(id =>
            {
                REPAIR_ORDERS order = obuDB.REPAIR_ORDERS.Find(id);
                //var order = obuDB.REPAIR_ORDERS.Find(id);
                if (order != null)
                {
                    //if (order.STATUS.ToInt() == RepairOrderStatus.InformedWithoutCustomer.ToInt())
                    //{
                    //    TimeSpan sp = new TimeSpan();
                    //    sp = DateTime.Now - order.MODIFY_DATE;
                    //    if (sp.Days > 0)
                    //    {
                    //        RepairOrderStatus status = RepairOrderStatus.InformedWithoutCustomer;
                    //        changRepariOrderStatus(order, status, u);
                    //    }
                    //    else
                    //    {
                    //        Ilist.Add(order);
                    //    }
                    //}
                    //else
                    //{
                    RepairOrderStatus status = RepairOrderStatus.InformedWithoutCustomer;
                    changRepariOrderStatus(order, status, u);
                    //success = true;
                    //}
                }
            });
            obuDB.SaveChanges();
            return Ilist;
        }

        /// <summary>
        /// 未联系上客户
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="u"></param>
        /// <returns></returns>
        public IList<REPAIR_ORDERS> ConnectionCustomers(IEnumerable<long> ids, OPERATOR u)
        {
            IList<REPAIR_ORDERS> Ilist = new List<REPAIR_ORDERS>();
            //bool success = false;
            ids.Each(id =>
                {
                    REPAIR_ORDERS order = obuDB.REPAIR_ORDERS.Find(id);
                    if (order != null)
                    {
                        if (order.STATUS.ToInt() == RepairOrderStatus.ConnectionWithoutCustomers.ToInt())
                        {  //如果维修单的状态为未联系上客户
                            DateTime trackingDate = new DateTime();
                            var tracking = (from i in obuDB.REPAIR_ORDER_TRACKING.ToList()
                                            where i.REPAIR_ORDER_ID == order.ID
                                            && i.REPAIR_ORDER_Status == RepairOrderStatus.ConnectionWithoutCustomers.ToInt()
                                            select i).OrderByDescending(m => m.CREATED_DATE).FirstOrDefault();
                            //先获取维修单操作未联系上客户的日期(不直接取维修单的modify_date是因为编辑也会导致modify_date的变更)
                            if (tracking != null)
                                trackingDate = tracking.CREATED_DATE;
                            else
                                trackingDate = order.MODIFY_DATE;

                            TimeSpan sp = new TimeSpan();
                            sp = DateTime.Now.Date - trackingDate.Date;
                            if (sp.Days > 0)
                            {
                                RepairOrderStatus status1 = RepairOrderStatus.ConnectionWithoutCustomers;
                                changRepariOrderStatus(order, status1, u);
                                order.CONFIRM_REPAIRED = Convert.ToInt32(ConfirmRepairedStatus.NotRepair);
                                RepairOrderStatus status2 = RepairOrderStatus.ConfirmedWithRepairByCustomer;
                                changRepariOrderStatus(order, status2, u);
                                //success = true;
                            }
                            else
                            {
                                Ilist.Add(order);
                            }
                        }
                        else
                        {
                            RepairOrderStatus status = RepairOrderStatus.ConnectionWithoutCustomers;
                            changRepariOrderStatus(order, status, u);
                            //success = true;
                        }
                    }
                });
            obuDB.SaveChanges();
            //return success;
            return Ilist;
        }
        /// <summary>
        /// 关闭维修单（客户未领取标签）
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="u"></param>
        /// <returns></returns>
        public bool CloseRepariOrder(IEnumerable<long> ids, OPERATOR u)
        {
            ids.Each(id =>
                {
                    var order = obuDB.REPAIR_ORDERS.Find(id);
                    if (order != null)
                    {
                        RepairOrderStatus status = RepairOrderStatus.ClosedWithoutCustomerPickedBack;
                        changRepariOrderStatus(order, status, u);
                    }
                });
            obuDB.SaveChanges();
            return true;
        }

        /// <summary>
        /// 判断选中的维修单状态是否一致
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool checkStatusIsSame(IEnumerable<long> ids)
        {
            if (ids == null)
                return true;
            var allItems = (from o in obuDB.REPAIR_ORDERS
                            where ids.Contains(o.ID)
                            select o.STATUS).Distinct();
            return allItems.Count() == 1;
        }

        /// <summary>
        /// 判断选中的维修单的厂商是否一致
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool checkSuppliersIsSame(IEnumerable<long> ids)
        {
            if (ids == null)
                return true;
            var allItems = (from o in obuDB.View_RepariOrders
                            where ids.Contains(o.ID)
                            select o.SUPPLIER).Distinct();
            return allItems.Count() == 1;
        }

        /// <summary>
        /// 修改维修单的状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        private bool changRepariOrderStatus(long id, RepairOrderStatus status, OPERATOR u)
        {
            var order = obuDB.REPAIR_ORDERS.Find(id);

            return this.changRepariOrderStatus(order, status, u);
        }

        /// <summary>
        /// 修改维修单的状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        private bool changRepariOrderStatus(REPAIR_ORDERS order, RepairOrderStatus status, OPERATOR u)
        {

            //记录修改前的状态
            RepairOrderStatus previousStatus = (RepairOrderStatus)order.STATUS;

            order.STATUS = status.ToInt().Value;
            order.MODIFY_BY = u.OPERATOR_NO;
            order.MODIFY_DATE = DateTime.Now;
            //obuDB.SaveChanges();

            LogRepairOrderTracking(order, previousStatus, u);
            return true;
        }
        /// <summary>
        /// 写维修单状态变化日志，已便于跟踪
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <param name="?"></param>
        /// <returns></returns>
        private bool LogRepairOrderTracking(REPAIR_ORDERS order, RepairOrderStatus previousStatus, OPERATOR u)
        {
            var tracking = new REPAIR_ORDER_TRACKING();
            tracking.CREATED_DATE = DateTime.Now;
            tracking.Operator_NO = u.OPERATOR_NO;
            tracking.REPAIR_ORDER_ID = order.ID;
            tracking.REPAIR_ORDER_Status = order.STATUS;
            string remark = "";

            RepairOrderStatus status = (RepairOrderStatus)order.STATUS;

            var v = obuDB.View_RepariOrders.Find(order.ID);
            string agent_name = ""; //作废的时候 需要重新获取营业厅名称，如果是维修组作废了营业厅->维修组的单子则显示待退回维修组描述
            if (v != null)
                agent_name = v.AGENT_NAME;

            switch (status)
            {
                case RepairOrderStatus.ReadyForReturnToRepairGroup:
                    remark = string.Format("{0}营业厅接收,待退回维修组", agent_name);
                    break;
                case RepairOrderStatus.ReturnedToRepairGroup:
                    remark = string.Format("{0}营业厅已退回维修组，待维修组确认接收", agent_name);
                    break;
                case RepairOrderStatus.ReadyForReturnToSupplier:
                    remark = string.Format("维修组确认接收,待返厂");
                    break;
                case RepairOrderStatus.ReturnedToSupplier:
                    remark = string.Format("维修组已返厂，待厂商返回报价");
                    break;
                case RepairOrderStatus.SupplierReturnedRepariPrice:
                    if (u.REMARK == "FLAG")
                        remark = string.Format("厂商返回报价");
                    else
                        remark = string.Format("厂商返回报价,待通知客户");
                    break;
                case RepairOrderStatus.ConfirmedWithRepairByCustomer:
                    var dictypeValue = configMgr.GetTypeValue(ConfigMgr.tblConfirmRepaired, order.CONFIRM_REPAIRED.ToString());
                    remark = string.Format("客户确认" + dictypeValue.DICT_TITLE + ",待通知厂商");
                    break;
                //case RepairOrderStatus.ConfirmedWithoutRepairByCustomer:
                //    remark = string.Format("客户确认不维修,待关闭");
                //    break;
                case RepairOrderStatus.InformeSupplierToRepair:
                    remark = string.Format("已将客户确认信息返给厂商");
                    break;
                case RepairOrderStatus.RepairedAndReturnedToRepariGroup:
                    remark = string.Format("标签已返回维修组");
                    break;
                case RepairOrderStatus.RepairedAndReturnedToAgent:
                    remark = string.Format("标签返回营业厅,待营业厅确认接收");
                    break;
                case RepairOrderStatus.ReadyForInformCustomer:
                    remark = string.Format("营业厅确认接收,待通知客户领取标签");
                    break;
                case RepairOrderStatus.InformedCustomer:
                    remark = string.Format("已通知客户领取标签");
                    break;
                case RepairOrderStatus.ClosedWithCustomerPickedBack:
                    remark = string.Format("客户领取标签,维修结束");
                    break;
                case RepairOrderStatus.ConnectionWithoutCustomers:
                    remark = string.Format("未联系上客户");
                    break;
                case RepairOrderStatus.InformedWithoutCustomer:
                    remark = string.Format("未联系上客户领取标签");
                    break;
                case RepairOrderStatus.ClosedWithoutCustomerPickedBack:
                    if (previousStatus == RepairOrderStatus.InformedCustomer)
                        remark = string.Format("已通知客户领取标签,但客户没有来领取标签，维修结束");
                    else if (order.CONFIRM_REPAIRED == ConfirmRepairedStatus.NotRepair.ToInt())
                        remark = "客户确认不维修标签，维修结束";
                    else
                        remark = "维修结束(客户未领取标签)";
                    break;
                case RepairOrderStatus.OneRepair:
                    remark = string.Format("{0}受理一口价维修", agent_name);
                    break;
            }

            tracking.REMARK = remark;
            obuDB.REPAIR_ORDER_TRACKING.Add(tracking);
            //obuDB.SaveChanges();
            return true;
        }

        /// <summary>
        /// 生成交易流水
        /// </summary>
        /// <returns></returns>
        public PRINT_LOG NewTransactionSerial(IList<long> logIDs, string USER_NO, OPERATOR u, IList<FUND_INFO> fundInfos)
        {
            PRINT_LOG pLog = null;
            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    pLog = new PRINT_LOG();

                    long id = logIDs.First();

                    var operLog = GetOperationLogs(id);

                    var dictTransactionType = configMgr.GetTypeValue(operLog.OPERATION_KIND);

                    pLog.AGENT_NO = u.AgentNo;
                    pLog.CLIENT_IP = u.CLIENT_IP;
                    pLog.CREATED_DATE = DateTime.Now;
                    pLog.OPERATOR_NO = u.OPERATOR_NO;
                    pLog.REMARK = "";
                    // pLog.SERIAL_NO = this.GetSerialOrderNO(u.AgentNo, (TransactionType)dictTransactionType.DICT_CODE.ToInt().Value, operLog.ID);
                    pLog.SERIAL_NO = this.GetSerialOrderNO(u.AgentNo, (TransactionType)operLog.OPERATION_KIND.ToInt().Value, operLog.ID);
                    pLog.USER_NO = USER_NO;

                    obuDB.PRINT_LOG.Add(pLog);

                    obuDB.SaveChanges(); //保存数据库，生成流水ID

                    logIDs.Each(logID =>
                    {
                        PRINT_DETAIL pd = new PRINT_DETAIL();
                        pd.LOG_ID = logID;
                        pd.SERIAL_ID = pLog.ID;
                        obuDB.PRINT_DETAIL.Add(pd);
                    });

                    fundInfos.Each
                        (
                            f =>
                            {
                                obuDB.FUND_INFO.Add(f);
                                obuDB.SaveChanges(); //生成资金来源ID
                                FUND_DETAIL fd = new FUND_DETAIL();
                                fd.SERIAL_ID = pLog.ID;
                                fd.FUND_ID = f.ID;
                                obuDB.FUND_DETAIL.Add(fd);
                            }
                        );

                    obuDB.SaveChanges();
                    scope.Complete();
                }
                catch (Exception ex)
                {
                    var msg = ex.Message;
                }
            }
            return pLog;
        }


        /// <summary>
        /// 生成发票
        /// </summary>
        /// <returns></returns>
        public bool NewInvoice(IList<long> logIDs, string USER_NO, OPERATOR u, IList<INVOICE_INFO> infos)
        {
            bool result = false;
            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    infos.Each
                       (
                           f =>
                           {
                               obuDB.INVOICE_INFO.Add(f);
                               obuDB.SaveChanges();
                               logIDs.Each(id =>
                               {
                                   INVOICE_DETAIL de = new INVOICE_DETAIL();
                                   de.INVOICE_ID = f.ID;
                                   de.SERIAL_ID = id;
                                   obuDB.INVOICE_DETAIL.Add(de);

                               });
                               obuDB.SaveChanges();
                           }
                       );
                    scope.Complete();
                    result = true;
                }
                catch (Exception ex)
                {
                    var msg = ex.Message;
                }
            }
            return result;
        }

        /// <summary>
        /// 交接单作废
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool CancelTransferBills(long[] ids, OPERATOR u, string remark)
        {
            var items = from t in obuDB.TRANSFER_BILLS
                        where ids.Contains(t.ID)
                        select t;

            items.Each(i =>
            {
                //修改交接单的状态为作废
                i.STATUS = (int)TransferStatus.Obsolete;
                i.MODIFY_BY = u.OPERATOR_NO;
                i.MODIFY_DATE = DateTime.Now;
                i.DeleteRemark = remark;

                //需要回滚的维修单状态
                RepairOrderStatus s = new RepairOrderStatus();

                TransferType transfer = (TransferType)i.TRANSFER_TYPE;
                //获取作废交接单的交接方向
                switch (transfer)
                {
                    case TransferType.AgentToRepairCenter:
                        s = RepairOrderStatus.ReadyForReturnToRepairGroup;
                        break;
                    case TransferType.RepairCenterToSupplier:
                        s = RepairOrderStatus.ReadyForReturnToSupplier;
                        break;
                    case TransferType.SupplierToRepairCenter:
                        s = RepairOrderStatus.InformeSupplierToRepair;
                        break;
                    case TransferType.RepairCenterToAgent:
                        s = RepairOrderStatus.RepairedAndReturnedToRepariGroup;
                        break;

                }
                //获取相关的交接单详情
                var TRANSFER_BILL_DETAILs = from d in obuDB.TRANSFER_BILL_DETAIL
                                            where ids.Contains(d.TRANSAFER_BILL_ID)
                                            select d;

                TRANSFER_BILL_DETAILs.Each(dt =>
                    {
                        ////获取上两次状态的变化
                        //var trackings = (from t in obuDB.REPAIR_ORDER_TRACKING
                        //                 where t.REPAIR_ORDER_ID == dt.REPAIR_ORDER_ID
                        //                 orderby t.CREATED_DATE descending
                        //                 select t).Take(2).ToList();
                        //REPAIR_ORDER_TRACKING tracking = null;
                        //if (trackings.Count() == 2)
                        //{
                        //    tracking = trackings[1];
                        //}
                        //else
                        //    tracking = trackings.First();
                        // changRepariOrderStatus(tracking.REPAIR_ORDER_ID, (RepairOrderStatus)tracking.REPAIR_ORDER_Status, u);
                        changRepariOrderStatus(dt.REPAIR_ORDER_ID, s, u);
                    });

            });



            obuDB.SaveChanges();
            return true;
        }

        public void Dispose()
        {
            obuDB.Dispose();
            rptDB.Dispose();
            configMgr.Dispose();
        }

        #region 查询数据

        public IEnumerable<View_RepariOrders> GetRepairOrders()
        {
            return obuDB.View_RepariOrders;
        }

        public IEnumerable<View_RepariOrders> GetRepairOrders(string sqlWhere)
        {
            if (!sqlWhere.IsNullOrEmpty())
                sqlWhere = sqlWhere.Trim();
            string sql = string.Format("SELECT * FROM [View_RepariOrders] {0} {1}", sqlWhere.IsNullOrEmpty() ? "" : "where", sqlWhere);
            return obuDB.Database.SqlQuery<View_RepariOrders>(sql);
        }

        public IEnumerable<View_Invoice_Info> GetInvoices(string sqlWhere)
        {
            if (!sqlWhere.IsNullOrEmpty())
                sqlWhere = sqlWhere.Trim();
            string sql = string.Format("SELECT * FROM [View_Invoice_Info] {0} {1}", sqlWhere.IsNullOrEmpty() ? "" : "where", sqlWhere);
            return obuDB.Database.SqlQuery<View_Invoice_Info>(sql);
        }
        /// <summary>
        /// 返回操作员每日发票统计
        /// </summary>
        /// <param name="sqlWhere"></param>
        /// <returns></returns>
        public IEnumerable<View_Operator_InvoiceInfos> GetOperatorInvoices(string sqlWhere)
        {
            if (!sqlWhere.IsNullOrEmpty())
                sqlWhere = sqlWhere.Trim();
            string sql = string.Format("SELECT * FROM [View_Operator_InvoiceInfos] {0} {1}", sqlWhere.IsNullOrEmpty() ? "" : "where", sqlWhere);
            return obuDB.Database.SqlQuery<View_Operator_InvoiceInfos>(sql);
        }

        /// <summary>
        /// 返回操作员每日收款退款统计
        /// </summary>
        /// <param name="sqlWhere"></param>
        /// <returns></returns>
        public IEnumerable<View_Received_Returned_Money> GetOperatorReceivedReturnedMoney(string sqlWhere)
        {
            if (!sqlWhere.IsNullOrEmpty())
                sqlWhere = sqlWhere.Trim();
            string sql = string.Format("SELECT * FROM [View_Received_Returned_Money] {0} {1}", sqlWhere.IsNullOrEmpty() ? "" : "where", sqlWhere);
            return obuDB.Database.SqlQuery<View_Received_Returned_Money>(sql);
        }

        public IEnumerable<View_Transaction_Serial_Info> GetTransactions(string sqlWhere)
        {
            if (!sqlWhere.IsNullOrEmpty())
                sqlWhere = sqlWhere.Trim();
            string sql = string.Format("SELECT * FROM [View_Transaction_Serial_Info] {0} {1}", sqlWhere.IsNullOrEmpty() ? "" : "where", sqlWhere);
            return obuDB.Database.SqlQuery<View_Transaction_Serial_Info>(sql);
        }
        //public IEnumerable<REPAIR_ORDERS> GetRepairOrders()
        //{
        //    return obuDB.REPAIR_ORDERS;
        //}

        public REPAIR_ORDERS GetRepairOrder(long id)
        {
            var order = obuDB.REPAIR_ORDERS.Find(id);
            return order;
        }

        public REPAIR_ORDERS GetRepairOrder(string repariOrderNo)
        {
            var order = from r in obuDB.REPAIR_ORDERS
                        where r.REPAIR_ORDER_NO.Equals(repariOrderNo)
                        select r;
            return order.FirstOrDefault();
        }

        public IEnumerable<REPAIR_ORDER_FAULT> GetRepairOrderFaults(long orderID)
        {
            var r = from f in obuDB.REPAIR_ORDER_FAULT
                    where f.REPAIR_ORDER_ID == orderID
                    select f;
            return r;
        }

        ///// <summary>
        ///// 获取报表库中的用户及车辆相关信息
        ///// </summary>
        ///// <param name="oubNo"></param>
        ///// <returns></returns>
        //public UserCarInfo GetUserCarInfo(string obuNo)
        //{
        //    return rptDB.GetUserCarInfo(obuNo);
        //}

        //public UserCarInfo GetUserCarInfo(string obuNo, string orderNo)
        //{
        //    return rptDB.GetUserCarInfo(obuNo);
        //}

        ///// <summary>
        ///// 获取库库中与标签型号及厂商相关的信息
        ///// </summary>
        ///// <param name="oubNo"></param>
        ///// <returns></returns>
        //public SupplierSpecInfo GetSupplierSpecInfo(string obuNo)
        //{
        //    string sql = string.Format("SELECT * from [View_OBU_Info] where '{0}' between start_no and end_no", obuNo);
        //    return obuDB.Database.SqlQuery<SupplierSpecInfo>(sql).FirstOrDefault();
        //}

        /// <summary>
        /// 根据标签号返回标签基本信息
        /// </summary>
        /// <param name="obuNo"></param>
        /// <returns></returns>
        public View_OBU_Info GetObuInfo(string obuNo)
        {
            var item = from o in obuDB.View_OBU_Info
                       where o.OBU_NO.Equals(obuNo)
                       select o;
            return item.FirstOrDefault();
        }

        public IEnumerable<TRANSFER_BILLS> GetTransferBills()
        {
            return this.obuDB.TRANSFER_BILLS;
        }

        public TRANSFER_BILLS GetTransferBill(long id)
        {
            return this.obuDB.TRANSFER_BILLS.Find(id);
        }

        public IEnumerable<TRANSFER_BILL_DETAIL> GetTransferBillDetails(long transferBillID)
        {
            var items = from item in obuDB.TRANSFER_BILL_DETAIL
                        where item.TRANSAFER_BILL_ID == transferBillID
                        select item;
            return items;
        }

        /// <summary>
        /// 根据sql查询交接单
        /// </summary>
        /// <param name="sqlWhere"></param>
        /// <returns></returns>
        public IEnumerable<View_TRANSFER_BILL_Info> GetTransferBills(string sqlWhere)
        {
            if (!sqlWhere.IsNullOrEmpty())
                sqlWhere = sqlWhere.Trim();
            string sql = string.Format("SELECT * FROM [View_TRANSFER_BILL_Info] {0} {1}", sqlWhere.IsNullOrEmpty() ? "" : "where", sqlWhere);
            return obuDB.Database.SqlQuery<View_TRANSFER_BILL_Info>(sql);
        }

        public View_TRANSFER_BILL_Info GetTransferBillViewInfo(long id)
        {
            return obuDB.View_TRANSFER_BILL_Info.Find(id);
        }


        /// <summary>
        /// 返回交易日志
        /// </summary>
        /// <param name="handled">
        /// True：则返回已经生成流水的
        /// False: 返回未生成流水的
        /// Null: 返回全部
        /// </param>
        /// <returns></returns>
        public IEnumerable<OPERATION_CARE_LOGS> GetOperationLogs(bool? handled)
        {
            string strOperationKind = " AND L.OPERATION_KIND!=" + (TransactionType.CollectsDeposit).ToInt();
            string sqlTeplate = @"SELECT l.[ID]
								  ,[OPERATION_KIND]
								  ,[POS_ID]
								  ,l.[OPERATOR_NO]
								  ,[OPERATION_ID]
								  ,[OBU_NO]
								  ,[AMOUNT]
								  ,[USER_NO]
								  ,[RECORD_TIME]
								  ,[CLIENT_IP]
								  ,l.[REMARK]
							  FROM [OPERATION_CARE_LOGS] l
							  left outer join PRINT_DETAIL p on p.LOG_ID=l.ID
							  left outer join dbo.INVOICE_DETAIL d on d.SERIAL_ID = p.SERIAL_ID
							  left outer join dbo.TRANSFER_BILL_DETAIL dbill on dbill.REPAIR_ORDER_ID = l.operation_id
							  left outer join dbo.TRANSFER_BILLS bill on  bill.id= dbill.TRANSAFER_BILL_ID
							  where (p.SERIAL_ID is {0} null or d.SERIAL_ID is {1}  null) " + strOperationKind;

            string sql = null;
            if (handled == null)
            {
                return obuDB.OPERATION_CARE_LOGS;
            }
            else
            {
                string isNot = handled.Value ? "not" : "";
                sql = string.Format(sqlTeplate, isNot, isNot);
            }

            return obuDB.Database.SqlQuery<OPERATION_CARE_LOGS>(sql);
        }
        /// <summary>
        /// 返回交易日志
        /// </summary>
        /// <param name="handled"></param>
        /// True：则返回已经生成流水的
        /// False: 返回未生成流水的
        /// Null: 返回全部
        /// <param name="sqlWhere">查询条件(维修单ID等)</param>
        /// <returns></returns>
        public IEnumerable<OPERATION_CARE_LOGS> GetOperationLogs(bool? handled, string sqlWhere)
        {
            string strOperationKind = " AND L.OPERATION_KIND!=" + (TransactionType.CollectsDeposit).ToInt() + sqlWhere;
            string sqlTeplate = @"SELECT l.[ID]
								  ,[OPERATION_KIND]
								  ,[POS_ID]
								  ,l.[OPERATOR_NO]
								  ,[OPERATION_ID]
								  ,[OBU_NO]
								  ,[AMOUNT]
								  ,[USER_NO]
								  ,[RECORD_TIME]
								  ,[CLIENT_IP]
								  ,l.[REMARK]
							  FROM [OPERATION_CARE_LOGS] l
							  left outer join PRINT_DETAIL p on p.LOG_ID=l.ID
							  left outer join dbo.TRANSFER_BILL_DETAIL dbill on dbill.REPAIR_ORDER_ID = l.operation_id
							  left outer join dbo.TRANSFER_BILLS bill on  bill.id= dbill.TRANSAFER_BILL_ID
							  where p.SERIAL_ID is {0} null  " + strOperationKind + " order by l.[RECORD_TIME] desc";
            //or d.SERIAL_ID is {1}  null)

            string sql = null;
            if (handled == null)
            {
                return obuDB.OPERATION_CARE_LOGS;
            }
            else
            {
                string isNot = handled.Value ? "not" : "";
                sql = string.Format(sqlTeplate, isNot, isNot);
            }

            return obuDB.Database.SqlQuery<OPERATION_CARE_LOGS>(sql);
        }



        /// <summary>
        /// 返回指定编号的交易日志
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public OPERATION_CARE_LOGS GetOperationLogs(long id)
        {
            return obuDB.OPERATION_CARE_LOGS.Find(id);
        }

        /// <summary>
        /// 返回指定编号的交易流水
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public PRINT_LOG GetPrintLogs(long id)
        {
            return obuDB.PRINT_LOG.Find(id);
        }


        public IEnumerable<REPAIR_ORDER_PRICE> GetRepairOrderPrices(string sqlWhere)
        {
            if (!sqlWhere.IsNullOrEmpty())
                sqlWhere = sqlWhere.Trim();
            string sql = string.Format("SELECT * FROM [REPAIR_ORDER_PRICE] {0} {1}", sqlWhere.IsNullOrEmpty() ? "" : "where", sqlWhere);
            return obuDB.Database.SqlQuery<REPAIR_ORDER_PRICE>(sql);
        }
        #endregion



        /// <summary>
        /// get repair_order info
        /// </summary>
        /// <param name="orderNo"></param>
        /// <param name="obuNo"></param>
        /// <returns></returns>
        public REPAIR_ORDERS getRepairOrderBy(string obuNo)
        {
            try
            {
                var order = from r in obuDB.REPAIR_ORDERS
                            where r.OBU_NO.Equals(obuNo)
                            select r;
                return order.FirstOrDefault();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// get repair_order info
        /// </summary>
        /// <param name="orderNo"></param>
        /// <param name="obuNo"></param>
        /// <returns></returns>
        public REPAIR_ORDERS getRepairOrderBy(string obuNo, string orderNo)
        {
            try
            {
                string strwhere = " where 1=1 ";//and STATUS> "+RepairOrderStatus.InformedCustomer.ToInt();
                if (obuNo != "") strwhere += " AND OBU_NO='" + obuNo + "'";
                if (orderNo != "") strwhere += " AND REPAIR_ORDER_NO='" + orderNo + "'";
                string sql = "SELECT * FROM REPAIR_ORDERS " + strwhere;
                return obuDB.Database.SqlQuery<REPAIR_ORDERS>(sql).FirstOrDefault();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        /// 获取维修性质名称
        /// </summary>
        /// <param name="typeID"></param>
        /// <returns></returns>
        public REPAIR_TYPE getRepairTypeValueBy(int typeID)
        {
            try
            {
                //string sql = "SELECT * FROM REPAIR_TYPE WHERE ID='" + typeID + "'";

                //return obuDB.Database.SqlQuery<REPAIR_TYPE>(sql).FirstOrDefault();
                return obuDB.REPAIR_TYPE.Find(typeID);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        /// 客户领取标签
        /// </summary>
        /// <param name="repairOrders"></param>
        /// <returns></returns>
        public bool GetObuBack(long id, bool returnSpareObu, string spareObuRemark, decimal? repairFee, decimal serviceFee, decimal serviceFeeAjust,
            string serviceFeeRemark, OPERATOR u)
        {
            bool result = false;
            try
            {
                var order = obuDB.REPAIR_ORDERS.Find(id);
                order.IS_RETURNED_SPARE_OBU = returnSpareObu;
                order.RETURNED_COMMENT = spareObuRemark;

                string logReMark = "领取标签：" + order.OBU_NO;
                if (order.CONFIRM_REPAIRED == ConfirmRepairedStatus.Repair.ToInt() || order.SPARE_OBU_PRICE.HasValue)
                {
                    //增加标签维修服务费的操作日志
                    LogtransactionLog(u, TransactionType.RepairServiceFee, order.ID, order.OBU_NO, serviceFee, order.USER_NO, logReMark);
                    //增加服务费生成信息
                    ServerFeeLog(order, Convert.ToInt32(AdjustType.GenerateServiceFee), serviceFeeAjust, serviceFeeRemark, u);
                    if (order.CONFIRM_REPAIRED == ConfirmRepairedStatus.Repair.ToInt())
                    {
                        //如果客户确认是维修 则增加日志 (因为流水单的打印是按日志来打的)
                        //增加维修费的操作日志
                        LogtransactionLog(u, TransactionType.RepairObu, order.ID, order.OBU_NO, repairFee, order.USER_NO, logReMark);
                    }
                    //如果有押金，则生成退还押金操作日志
                    if (order.SPARE_OBU_PRICE.HasValue)
                    {
                        decimal deposit = -order.SPARE_OBU_PRICE.Value;
                        LogtransactionLog(u, TransactionType.ReturnDeposit, order.ID, order.OBU_NO, deposit, order.USER_NO, logReMark);
                    }
                }





                //更新维修单状态信息
                changRepariOrderStatus(order, RepairOrderStatus.ClosedWithCustomerPickedBack, u);

                obuDB.SaveChanges();

                result = true;
            }
            catch (Exception ex)
            {

                throw ex;
            }
            return result;

        }

        #region 生成单据号

        /// <summary>
        /// 生成维修单号
        /// </summary>
        /// <param name="agentno"></param>
        /// <returns></returns>
        public string GetRepairOrderNO(string agentno)
        {
            StringBuilder repairorderno = new StringBuilder(agentno);
            repairorderno.Append(DateTime.Now.ToString("yyyyMMdd"));

            DateTime enddate = DateTime.Now.AddDays(1);
            //var lastOder = (from o in obuDB.REPAIR_ORDERS
            //                where o.AGENT_NO.Equals(agentno) && o.CREATED_DATE >= DateTime.Today
            //                orderby o.CREATED_DATE descending
            //                select o).Take(1).FirstOrDefault();
            var lastOder = (from o in obuDB.REPAIR_ORDERS
                            where o.AGENT_NO.Equals(agentno) && o.CREATED_DATE >= DateTime.Today && o.CREATED_DATE < enddate
                            orderby o.CREATED_DATE descending
                            select o).Take(1).FirstOrDefault();
            int serialNumber = 0;
            if (lastOder != null)
            {
                string lastRepairNo = lastOder.REPAIR_ORDER_NO;
                serialNumber = lastRepairNo.Substring(lastRepairNo.Length - 4, 4).ToInt().Value;
            }
            serialNumber += 1;

            repairorderno.Append(serialNumber.ToString().PadLeft(4, '0'));
            return repairorderno.ToString();
        }
        /// <summary>
        /// 生成流水单号 营业厅编号+日期+操作类型code+日志操作ID
        /// </summary>
        /// <param name="agentno">营业厅编号</param>
        /// <param name="operationtype">操作类型code</param>
        /// <param name="operationid">日志操作ID</param>
        /// <returns></returns>
        public string GetSerialOrderNO(string agentno, TransactionType transactionType, long operationid)
        {
            StringBuilder serialorderno = new StringBuilder(agentno);
            serialorderno.Append(DateTime.Now.ToString("yyyyMMdd"));

            var stroperationid = operationid.ToText();
            // stroperationid = stroperationid.Substring(stroperationid.Length - 2, 2);
            serialorderno.Append(transactionType.ToInt().ToText());
            serialorderno.Append(stroperationid);
            return serialorderno.ToString();
        }
        static int year = 2000;
        /// <summary>
        /// 生成交接单号
        /// </summary>
        /// <param name="tradetype"></param>
        /// <returns></returns>
        public string GetTransferOrderNO(TransferType transferType)
        {
            StringBuilder no = new StringBuilder();
            no.Append(DateTime.Now.ToString("yyyyMMdd"));
            var lastBill = (from o in obuDB.TRANSFER_BILLS
                            where o.CREATED_DATE >= DateTime.Today
                            orderby o.CREATED_DATE descending
                            select o).Take(1).FirstOrDefault();

            no.Append(transferType.ToInt().ToText().PadLeft(2, '0'));

            int serialNumber = 0;
            if (CheckNewYear() && year != DateTime.Now.Year)
            {
                year = DateTime.Now.Year;
                no.Append(serialNumber.ToString().PadLeft(6, '0'));
                return no.ToString();
            }
            if (lastBill != null)
            {
                string lastNo = lastBill.TRANSFER_BILL_NO;
                serialNumber = lastNo.Substring(lastNo.Length - 4, 4).ToInt().Value;
            }
            serialNumber += 1;

            no.Append(serialNumber.ToString().PadLeft(6, '0'));
            return no.ToString();
        }

        public bool CheckNewYear()
        {
            int now = DateTime.Now.Year;
            int old = DateTime.Now.AddDays(-1).Year;
            return (now - old) == 1;
        }

        #endregion
        /// <summary>
        /// 获取维修费、服务费、调整费等信息
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        public IEnumerable<REPAIR_ORDER_ADJUST> getRepairFeeAdjust(long orderID, AdjustType adjustType)
        {
            int adjustTypeInt = adjustType.ToInt().Value;
            var r = from f in obuDB.REPAIR_ORDER_ADJUST
                    where f.REPAIR_ORDER_ID == orderID && f.ADJUST_TYPE == adjustTypeInt
                    select f;
            return r;
        }
        /// <summary>
        /// 获取故障点
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        public IEnumerable<REPAIR_ORDER_PRICE> getRepairFee(long orderID)
        {
            var r = from f in obuDB.REPAIR_ORDER_PRICE
                    where f.REPAIR_ORDER_ID == orderID && f.PRICE_FLAG != ConfigMgr.PriceFlag_Invalid
                    select f;
            return r;
        }

        #region 查询相关代码

        /// <summary>
        /// 根据这些参数，返回相应查询的sql
        /// </summary>
        /// <param name="FromCreatedDate"></param>
        /// <param name="ToCreatedDate"></param>
        /// <param name="RepairOrderNO"></param>
        /// <param name="ObuNO"></param>
        /// <param name="Supplier"></param>
        /// <param name="Status"></param>
        /// <param name="Agent"></param>
        /// <param name="Operator"></param>
        /// <param name="IsNeedSpareObu"></param>
        /// <returns></returns>
        public string GetSearhRepairOrdersSql(DateTime? FromCreatedDate, DateTime? ToCreatedDate, string RepairOrderNO,
            string ObuNO, string Supplier, string Status, string Agent, string Operator, string IsNeedSpareObu,
            string Vehicle_Plate_No, string Mobile_No, string ConfirmRepaired, string operatorNo)
        {
            List<string> querys = new List<string>();
            if (FromCreatedDate.HasValue)
            {
                querys.Add(string.Format(" REPORT_DATE>='{0}' ", FromCreatedDate.Value.ToString("yyyy-MM-dd")));
            }

            if (ToCreatedDate.HasValue)
            {
                querys.Add(string.Format(" REPORT_DATE<'{0}' ", ToCreatedDate.Value.AddDays(1).ToString("yyyy-MM-dd")));
            }

            if (!RepairOrderNO.IsNullOrEmpty())
            {
                querys.Add(string.Format(" REPAIR_ORDER_NO like '%{0}%' ", RepairOrderNO));
            }

            if (!ObuNO.IsNullOrEmpty())
            {
                querys.Add(string.Format(" OBU_NO like '%{0}%' ", ObuNO));
            }

            if (!Supplier.IsNullOrEmpty())
            {
                querys.Add(string.Format(" SUPPLIERS_ID='{0}' ", Supplier));
            }

            if (!Status.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [STATUS]={0} ", Status));
            }

            if (!Agent.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [AGENT_NO]='{0}' ", Agent));
            }

            if (!Operator.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [CREATED_BY]='{0}' ", Operator));
            }
            if (!operatorNo.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [CREATED_BY]='{0}' ", operatorNo));
            }
            if (!IsNeedSpareObu.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [IsNeedSPARE_OBU]='{0}' ", IsNeedSpareObu));
            }
            if (!Vehicle_Plate_No.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [VEHICLE_PLATE_NO] LIKE '%{0}%'", Vehicle_Plate_No));
            }
            if (!Mobile_No.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [MOBILE_TEL_NO] LIKE '%{0}%'", Mobile_No));
            }
            if (!ConfirmRepaired.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [CONFIRM_REPAIRED]='{0}'", ConfirmRepaired));
            }
            return querys.ConcatToString(" and ");
        }

        /// <summary>
        /// 根据这些参数，返回相应查询的sql
        /// </summary>
        /// <param name="FromCreatedDate"></param>
        /// <param name="ToCreatedDate"></param>
        /// <param name="InvoiceType"></param>
        /// <param name="UserNo"></param>
        /// <param name="SERIAL_NO"></param>
        /// <param name="Operator"></param>
        /// <param name="AgentType"></param>
        /// <param name="Agent"></param>
        /// <returns></returns>
        public string GetSearhInvoiceReportSql(DateTime? FromCreatedDate, DateTime? ToCreatedDate, string InvoiceType, string UserNo,
            string SERIAL_NO, string Operator, string AgentType, string Agent, string operatorNo)
        {
            List<string> querys = new List<string>();
            if (FromCreatedDate.HasValue)
            {
                querys.Add(string.Format(" [INCOICE_TIME]>='{0}' ", FromCreatedDate.Value.ToString("yyyy-MM-dd")));
            }

            if (ToCreatedDate.HasValue)
            {
                querys.Add(string.Format(" [INCOICE_TIME]<'{0}' ", ToCreatedDate.Value.AddDays(1).ToString("yyyy-MM-dd")));
            }

            if (!InvoiceType.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [INVOICE_TYPE] = {0} ", InvoiceType));
            }

            if (!UserNo.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [USER_NO] like '%{0}%' ", UserNo));
            }

            if (!SERIAL_NO.IsNullOrEmpty())
            {
                querys.Add(string.Format(" SERIAL_NO like '%{0}%' ", SERIAL_NO));
            }

            if (!AgentType.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [AGENT_TYPE_NO]='{0}' ", AgentType));
            }

            if (!Agent.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [AGENT_NO]='{0}' ", Agent));
            }

            if (!Operator.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [OPERATOR_NO]='{0}' ", Operator));
            }
            if (!operatorNo.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [OPERATOR_NO]='{0}' ", operatorNo));
            }

            return querys.ConcatToString(" and ");
        }


        public string GetSearhTransactionReportSql(DateTime? FromCreatedDate, DateTime? ToCreatedDate, string TransactionType, string UserNo,
            string SERIAL_NO, string Operator, string AgentType, string Agent, string operatorNo)
        {
            List<string> querys = new List<string>();
            if (FromCreatedDate.HasValue)
            {
                querys.Add(string.Format(" [RECORD_TIME]>='{0}' ", FromCreatedDate.Value.ToString("yyyy-MM-dd")));
            }

            if (ToCreatedDate.HasValue)
            {
                querys.Add(string.Format(" [RECORD_TIME]<'{0}' ", Convert.ToDateTime(ToCreatedDate.Value).AddDays(1)));
            }

            if (!TransactionType.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [OPERATION_KIND] = {0} ", TransactionType));
            }

            if (!UserNo.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [USER_NO] like '%{0}%' ", UserNo));
            }

            if (!SERIAL_NO.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [SERIAL_NO] like '%{0}%' ", SERIAL_NO));
            }

            if (!AgentType.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [AGENT_TYPE_NO]='{0}' ", AgentType));
            }

            if (!Agent.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [AGENT_NO]='{0}' ", Agent));
            }

            if (!Operator.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [tLogOperator]='{0}' ", Operator));
            }
            if (!operatorNo.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [tLogOperator]='{0}' ", operatorNo));
            }

            return querys.ConcatToString(" and ");
        }

        public string GetSearhDailyReportSql(DateTime? FromCreatedDate, DateTime? ToCreatedDate,
           string Operator, string Agent, string operatorNo)
        {
            List<string> querys = new List<string>();
            if (FromCreatedDate.HasValue)
            {
                querys.Add(string.Format(" [RECORD_TIME]>='{0}' ", FromCreatedDate.Value.ToString("yyyy-MM-dd")));
            }

            if (ToCreatedDate.HasValue)
            {
                querys.Add(string.Format(" [RECORD_TIME]<'{0}' ", ToCreatedDate.Value.AddDays(1).ToString("yyyy-MM-dd")));
            }

            if (!Agent.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [AGENT_NO]='{0}' ", Agent));
            }

            if (!Operator.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [OPERATOR_NO]='{0}' ", Operator));
            }
            if (!operatorNo.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [OPERATOR_NO]='{0}' ", operatorNo));
            }

            return querys.ConcatToString(" and ");
        }


        public string GetSearhTransferBillsSql(DateTime? FromCreatedDate, DateTime? ToCreatedDate,
            string Supplier, string TRANSFER_TYPE, string AgentType, string Agent,
            string TransferBillStatus, string normalAgentNo)
        {
            List<string> querys = new List<string>();
            if (FromCreatedDate.HasValue)
            {
                querys.Add(string.Format(" TRANSFER_DATE>='{0}' ", FromCreatedDate.Value.ToString("yyyy-MM-dd")));
            }

            if (ToCreatedDate.HasValue)
            {
                querys.Add(string.Format(" TRANSFER_DATE<'{0}' ", ToCreatedDate.Value.AddDays(1).ToString("yyyy-MM-dd")));
            }


            if (!Supplier.IsNullOrEmpty())
            {
                string str = normalAgentNo.Trim() == "" ? " (TRANSFER_FROM ='" + Supplier + "' OR TRANSFER_TO='" + Supplier + "') "
                    : "( (TRANSFER_FROM ='" + Supplier + "' AND TRANSFER_TO='" + normalAgentNo + "') OR( TRANSFER_FROM='"
                    + normalAgentNo + "'AND TRANSFER_TO='" + Supplier + "' ) ) ";
                querys.Add(string.Format(" {0} ", str));
            }

            if (!TRANSFER_TYPE.IsNullOrEmpty())
            {
                querys.Add(string.Format(" TRANSFER_TYPE={0} ", TRANSFER_TYPE));
            }

            if (!Agent.IsNullOrEmpty())
            {
                querys.Add(string.Format(" ( TRANSFER_FROM ='{0}' OR TRANSFER_TO='{1}') ", Agent, Agent));
            }

            if (!AgentType.IsNullOrEmpty())
            {
                querys.Add(string.Format(" AGENT_TYPE_NO='{0}' ", AgentType));
            }

            if (!TransferBillStatus.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [STATUS]='{0}' ", TransferBillStatus));
            }

            return querys.ConcatToString(" and ");
        }
        /// <summary>
        /// 获取维修日报查询条件
        /// </summary>
        /// <param name="FromCreatedDate"></param>
        /// <param name="ToCreatedDate"></param>
        /// <param name="InvoiceType"></param>
        /// <param name="UserNo"></param>
        /// <param name="SERIAL_NO"></param>
        /// <param name="Operator"></param>
        /// <param name="AgentType"></param>
        /// <param name="Agent"></param>
        /// <param name="operatorNo"></param>
        /// <returns></returns>
        public string GetRepairDailySearch(DateTime? FromCreatedDate, DateTime? ToCreatedDate, string Agent, string operatorNo)
        {
            List<string> querys = new List<string>();
            if (FromCreatedDate.HasValue)
            {
                querys.Add(string.Format(" [RECORD_TIME]>='{0}' ", FromCreatedDate.Value.ToString("yyyy-MM-dd")));
            }

            if (ToCreatedDate.HasValue)
            {
                querys.Add(string.Format(" [RECORD_TIME]<'{0}' ", ToCreatedDate.Value.AddDays(1).ToString("yyyy-MM-dd")));
            }
            if (!Agent.IsNullOrEmpty())
            {
                querys.Add(string.Format(" C.[AGENT_NO]='{0}' ", Agent));
            }

            if (!operatorNo.IsNullOrEmpty())
            {
                querys.Add(string.Format(" C.[OPERATOR_NO]='{0}' ", operatorNo));
            }
            return querys.ConcatToString(" and ");
        }

        #endregion


        #region 元器件相关

        /// <summary>
        /// 删除型号配置
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeletePartSpec(int id)
        {
            var r = (from s in obuDB.PARTS_STOCK
                     where s.PARTS_SPEC_ID == id
                     select s).FirstOrDefault();
            if (r != null)
                throw new Exception("此型号已经入过库，无法删除");

            var spec = this.obuDB.PARTS_SPECS.Find(id);
            if (spec != null)
            {
                int delStatus = DictTypeStatus.Deleted.ToInt().Value;
                var dts = (from dt in obuDB.PARTS_SPECS_DETAIL
                           where dt.PARTS_SPEC_ID == id && dt.STATUS != delStatus
                           select dt).ToList();

                int notUsedStatus = DictTypeStatus.NotUsed.ToInt().Value;
                dts.Each(t => t.STATUS = notUsedStatus);
                spec.STATUS = notUsedStatus;

                obuDB.SaveChanges();
            }

            return true;
        }


        public bool PartsStockIn(IEnumerable<PARTS_STOCK> items)
        {
            items.Each(item =>
                {
                    obuDB.PARTS_STOCK.Add(item);
                });

            obuDB.SaveChanges();

            return true;
        }


        /// <summary>
        /// 销售元器件
        /// </summary>
        /// <param name="data"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public long SellParts(List<PartsSellInfo> data, OPERATOR user)
        {
            long id = -1;
            using (TransactionScope scope = new TransactionScope())
            {
                try
                {
                    data.Each(d =>
                    {
                        var info = new PARTS_SALE();
                        // var obuInfo = GetObuInfo(d.Obu_No);
                        var v = getObuInfoByObu(d.Obu_No);
                        info.AGENT_NO = user.AgentNo;
                        info.AMOUNT = d.Price;
                        info.CREATED_BY = user.OPERATOR_NO;
                        info.CREATED_DATE = DateTime.Now;
                        info.Modify_by = user.OPERATOR_NO;
                        info.Modify_date = DateTime.Now;
                        info.OBU_NO = d.Obu_No;
                        info.OBU_REGISTE_DATE = Convert.ToDateTime(v.REGISTE_DATE);
                        // info.OBU_REGISTE_DATE= obuInfo.REGISTE_DATE.Value;
                        info.PARTS_ID = d.PartTypeID;
                        info.PARTS_SPEC_ID = d.SpecID;
                        info.REMARK = d.Comments == null ? "" : d.Comments; ;
                        info.REPORT_DATE = DateTime.Now;
                        info.SPEC_NAME = d.Spec;
                        info.STATUS = DictTypeStatus.Normal.ToInt().Value;
                        info.SUPPLIER_ID = d.SupplierID;
                        info.SUPPLIER_NAME = d.Supplier;
                        info.USER_NO = v.USER_NO;
                        // info.USER_NO = obuInfo.USER_NO;

                        this.obuDB.PARTS_SALE.Add(info);

                        obuDB.SaveChanges();

                        TransactionType tType = TransactionType.IssueSpareTape;
                        string reMark = "备胶销售";
                        if (info.PARTS_ID == ConfigMgr.PartBaseID)
                        {
                            tType = TransactionType.IssueBase;
                            reMark = "底座销售：";
                        }
                        reMark += info.AMOUNT.ToText();
                        var log = LogtransactionLog(user, tType, info.ID, info.OBU_NO, info.AMOUNT, info.USER_NO, reMark);
                        obuDB.SaveChanges();
                        id = log.ID;
                    });

                    scope.Complete();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            return id;
        }

        /// <summary>
        /// 划拨冲正
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Reversal(int id, OPERATOR oper)
        {
            bool r = false;
            var sourceTransfer = obuDB.PARTS_TRANSFER.Find(id);
            sourceTransfer.Status = DictTypeStatus.Deleted.ToInt().Value;
            //sourceTransfer.TRANSFER_KIND=Parts_Transfer_Kind.Reversal.ToInt().Value;

            PARTS_TRANSFER rTransfer = new PARTS_TRANSFER();
            rTransfer.AGENT_NO = sourceTransfer.OWNER;
            rTransfer.CREATED_BY = oper.OPERATOR_NO;
            rTransfer.CREATED_DATE = DateTime.Now;
            rTransfer.OWNER = sourceTransfer.AGENT_NO;
            rTransfer.PARTS_COUNT = sourceTransfer.PARTS_COUNT;
            rTransfer.PARTS_ID = sourceTransfer.PARTS_ID;
            rTransfer.PARTS_SPEC_ID = sourceTransfer.PARTS_SPEC_ID;
            rTransfer.RECORD_DATE = DateTime.Now;
            rTransfer.Remark = "冲正划拨编号：" + sourceTransfer.ID;
            rTransfer.Reversal_ID = sourceTransfer.ID;
            rTransfer.SPEC_NAME = sourceTransfer.SPEC_NAME;
            rTransfer.Status = DictTypeStatus.Normal.ToInt().Value;
            rTransfer.SUPPLIER_ID = sourceTransfer.SUPPLIER_ID;
            rTransfer.SUPPLIER_NAME = sourceTransfer.SUPPLIER_NAME;
            rTransfer.TRANSFER_KIND = Parts_Transfer_Kind.Reversal.ToInt().Value;
            obuDB.PARTS_TRANSFER.Add(rTransfer);

            if (transfer(rTransfer))
                obuDB.SaveChanges();
            r = true;

            return r;
        }
        /// <summary>
        /// 入库冲正
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool StockCallBack(int id, OPERATOR oper)
        {
            bool r = false;
            var sourceTransfer = obuDB.PARTS_STOCK.Find(id);
            sourceTransfer.status = DictTypeStatus.Deleted.ToInt().Value;

            PARTS_STOCK rTransfer = new PARTS_STOCK();
            rTransfer.OWNER = sourceTransfer.OWNER;
            rTransfer.CREATED_BY = oper.OPERATOR_NO;
            rTransfer.CREATED_DATE = DateTime.Now;
            rTransfer.PARTS_COUNT = -sourceTransfer.PARTS_COUNT;
            rTransfer.PARTS_ID = sourceTransfer.PARTS_ID;
            rTransfer.PARTS_SPEC_ID = sourceTransfer.PARTS_SPEC_ID;
            rTransfer.RECORD_DATE = DateTime.Now;
            rTransfer.In_Stock_ID = sourceTransfer.ID;
            rTransfer.SPEC_NAME = sourceTransfer.SPEC_NAME;
            rTransfer.SUPPLIER_ID = sourceTransfer.SUPPLIER_ID;
            rTransfer.SUPPLIER_NAME = sourceTransfer.SUPPLIER_NAME;
            obuDB.PARTS_STOCK.Add(rTransfer);
            obuDB.SaveChanges();
            r = true;

            return r;
        }

        /// <summary>
        /// 划拨，调库，冲正
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public bool Transfer(IList<PARTS_TRANSFER> items)
        {
            var centerAgent = configMgr.GetCenterAgentNo();//获取中心库


            using (TransactionScope scope = new TransactionScope())
            {
                items.Each(item =>
                    {
                        //owner是中心库时，则是划拨
                        if (item.OWNER.Equals(centerAgent.AgentNo))
                        {
                            item.TRANSFER_KIND = Parts_Transfer_Kind.Transfer.ToInt().Value;
                        }
                        else if (item.AGENT_NO.Equals(centerAgent.AgentNo))//如果发行代理是中心库，则是退库
                        {
                            item.TRANSFER_KIND = Parts_Transfer_Kind.Return.ToInt().Value;
                        }
                        else //否则就是调库
                            item.TRANSFER_KIND = Parts_Transfer_Kind.Change.ToInt().Value;
                        this.obuDB.PARTS_TRANSFER.Add(item);
                        obuDB.SaveChanges();

                        transfer(item);


                    });

                obuDB.SaveChanges();

                scope.Complete();
            }

            return true;
        }

        /// <summary>
        /// 根据交接信息生成入库和出库记录
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        private bool transfer(PARTS_TRANSFER t)
        {
            //入库
            PARTS_STOCK inS = createPARTS_STOCK(t);
            inS.OWNER = t.AGENT_NO;
            inS.PARTS_COUNT = t.PARTS_COUNT;

            //出库
            PARTS_STOCK outS = createPARTS_STOCK(t);
            inS.OWNER = t.OWNER;
            inS.PARTS_COUNT = -t.PARTS_COUNT;

            obuDB.PARTS_STOCK.Add(inS);
            obuDB.PARTS_STOCK.Add(outS);
            //obuDB.SaveChanges();
            return true;
        }

        private PARTS_STOCK createPARTS_STOCK(PARTS_TRANSFER t)
        {
            PARTS_STOCK inS = new PARTS_STOCK();
            inS.CREATED_BY = t.CREATED_BY;
            inS.CREATED_DATE = t.CREATED_DATE;
            inS.OWNER = t.AGENT_NO;
            inS.PARTS_COUNT = t.PARTS_COUNT;
            inS.PARTS_ID = t.PARTS_ID;
            inS.PARTS_SPEC_ID = t.PARTS_SPEC_ID;
            inS.RECORD_DATE = t.RECORD_DATE;
            inS.SPEC_NAME = t.SPEC_NAME;
            inS.status = DictTypeStatus.Normal.ToInt().Value;
            inS.SUPPLIER_ID = t.SUPPLIER_ID;
            inS.SUPPLIER_NAME = t.SUPPLIER_NAME;

            inS.TransferID = t.ID;//交接时，要记录相关的交接单号

            return inS;
        }


        /// <summary>
        /// 返回元器件划拨冲正
        /// </summary>
        /// <param name="sqlWhere"></param>
        /// <returns></returns>
        public IEnumerable<View_Parts_Transfer> GetPartsTransfers(string sqlWhere)
        {
            if (!sqlWhere.IsNullOrEmpty())
                sqlWhere = sqlWhere.Trim();
            string sql = string.Format("SELECT * FROM [View_Parts_Transfer] {0} {1}", sqlWhere.IsNullOrEmpty() ? "" : "where", sqlWhere);
            return obuDB.Database.SqlQuery<View_Parts_Transfer>(sql);
        }

        public string GetSearhReversalSql(DateTime? FromCreatedDate, DateTime? ToCreatedDate, string Supplier, string SpecName,
            string sAgentType, string sAgent, string AgentType, string Agent, string PartType, string TransferKind)
        {
            List<string> querys = new List<string>();
            if (FromCreatedDate.HasValue)
            {
                querys.Add(string.Format(" [RECORD_DATE]>='{0}' ", FromCreatedDate.Value.ToString("yyyy-MM-dd")));
            }

            if (ToCreatedDate.HasValue)
            {
                querys.Add(string.Format(" [RECORD_DATE]<'{0}' ", ToCreatedDate.Value.AddDays(1).ToString("yyyy-MM-dd")));
            }

            if (!Supplier.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [SUPPLIER_ID]={0} ", Supplier));
            }
            if (!SpecName.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [PARTS_SPEC_ID]={0} ", SpecName));
            }

            if (!AgentType.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [AgentTypeNo]='{0}' ", AgentType));
            }

            if (!Agent.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [AGENT_NO]='{0}' ", Agent));
            }

            if (!sAgentType.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [OwnerTypeNo]='{0}' ", sAgentType));
            }

            if (!sAgent.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [OwnerNo]='{0}' ", sAgent));
            }

            if (!PartType.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [PARTS_ID]={0} ", PartType));
            }

            if (!TransferKind.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [TRANSFER_KIND]={0} ", TransferKind));
            }



            return querys.ConcatToString(" and ");
        }

        /// <summary>
        /// 根据选择的入库类别 获取对应的查询条件
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string GetStrWhereByInStockBy(string value)
        {
            string str = "";
            switch (value)
            {
                case "1": //正常入库
                    str = " TRANSFERID IS NULL AND IN_STOCK_ID IS NULL AND STATUS=0";
                    break;
                case "2": //入库被冲正
                    str = " TRANSFERID IS NULL AND IN_STOCK_ID IS NULL AND STATUS=" + DictTypeStatus.Deleted.ToInt().Value;
                    break;
                case "3": //入库冲正
                    str = " TRANSFERID IS NULL AND IN_STOCK_ID>0 ";
                    break;
                default:
                    str = "";
                    break;

            }
            return str;
        }
        public string GetSearhPartsStockInSql(DateTime? FromCreatedDate, DateTime? ToCreatedDate, string Supplier, string SpecName, string PartType,
            string Stock_type)
        {
            List<string> querys = new List<string>();
            if (FromCreatedDate.HasValue)
            {
                querys.Add(string.Format(" [RECORD_DATE]>='{0}' ", FromCreatedDate.Value.ToString("yyyy-MM-dd")));
            }

            if (ToCreatedDate.HasValue)
            {
                querys.Add(string.Format(" [RECORD_DATE]<'{0}' ", ToCreatedDate.Value.AddDays(1).ToString("yyyy-MM-dd")));
            }

            if (!Supplier.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [SUPPLIER_ID]={0} ", Supplier));
            }
            if (!SpecName.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [PARTS_SPEC_ID]={0} ", SpecName));
            }
            if (!PartType.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [PARTS_ID]={0} ", PartType));
            }
            if (!Stock_type.IsNullOrEmpty())
            {
                string str = GetStrWhereByInStockBy(Stock_type);
                querys.Add(string.Format(" {0} ", str));
            }

            return querys.ConcatToString(" and ");
        }

        /// <summary>
        /// 获取元器件入库信息
        /// </summary>
        /// <param name="sqlWhere"></param>
        /// <returns></returns>
        public IEnumerable<View_PartsStockDetails> GetPartsStockIn(string sqlWhere)
        {
            if (!sqlWhere.IsNullOrEmpty())
                sqlWhere = sqlWhere.Trim();
            string sql = string.Format("SELECT * FROM [View_PartsStockDetails] {0} {1}", sqlWhere.IsNullOrEmpty() ? "" : "where", sqlWhere);
            return obuDB.Database.SqlQuery<View_PartsStockDetails>(sql);
        }

        /// <summary>
        /// 获取元器件销售信息
        /// </summary>
        /// <param name="sqlWhere"></param>
        /// <returns></returns>
        public IEnumerable<View_PARTS_SALE> GetPartsSale(string sqlWhere)
        {
            if (!sqlWhere.IsNullOrEmpty())
                sqlWhere = sqlWhere.Trim();
            string sql = string.Format("SELECT * FROM [View_PARTS_SALE] {0} {1}", sqlWhere.IsNullOrEmpty() ? "" : "where", sqlWhere);
            return obuDB.Database.SqlQuery<View_PARTS_SALE>(sql);
        }

        public string GetSearhPartsSaleSql(DateTime? FromCreatedDate, DateTime? ToCreatedDate, string PartType, string Supplier, string SpecName,
            string AgentType, string Agent, string Operator, string ObuNo, string Amount)
        {
            List<string> querys = new List<string>();

            if (FromCreatedDate.HasValue)
            {
                querys.Add(string.Format(" REPORT_DATE>='{0}' ", FromCreatedDate.Value.ToString("yyyy-MM-dd")));
            }

            if (ToCreatedDate.HasValue)
            {
                querys.Add(string.Format(" REPORT_DATE<'{0}' ", ToCreatedDate.Value.AddDays(1).ToString("yyyy-MM-dd")));
            }

            if (!PartType.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [PARTS_ID]={0} ", PartType));
            }

            if (!Supplier.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [SUPPLIER_ID]={0} ", Supplier));
            }
            if (!SpecName.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [PARTS_SPEC_ID]={0} ", SpecName));
            }
            if (!AgentType.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [AGENT_TYPE_NO]='{0}' ", AgentType));
            }
            if (!Agent.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [AGENT_NO]='{0}' ", Agent));
            }
            if (!ObuNo.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [OBU_NO] like '%{0}%' ", ObuNo));
            }
            if (!Amount.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [AMOUNT]='{0}'", Amount));
            }
            if (!Operator.IsNullOrEmpty())
            {
                querys.Add(string.Format(" [CREATED_BY]='{0}'", Operator));
            }
            return querys.ConcatToString(" and ");
        }
        /// <summary>
        /// 根据标签号获取最新的发行日期、客户编号、Last_obu_no
        /// </summary>
        /// <param name="obu_no">标签号</param>
        /// <returns></returns>
        public View_OBU_INFO_BY getObuInfoByObu(string obu_no)
        {
            string sql = "SELECT * FROM  View_OBU_INFO_BY WHERE OBU_NO='" + obu_no + "' ORDER BY REGISTE_DATE DESC ";
            IEnumerable<View_OBU_INFO_BY> r = obuDB.Database.SqlQuery<View_OBU_INFO_BY>(sql).ToList();
            var obu = new View_OBU_INFO_BY();
            if (r != null && r.Count() > 0)
            {
                obu = r.FirstOrDefault();
            }
            else
            {
                obu.OBU_NO = obu_no;
                obu.REGISTE_DATE = DateTime.Now;
                obu.LAST_OBU_NO = "";
                obu.USER_NO = "00000000000000";
            }
            return obu;
        }
        #endregion


        /// <summary>
        /// 得到以旧换翻新更换和回收之前的标签号
        /// </summary>
        /// <param name="obuNo">当前标签号</param>
        /// <returns>查询到的标签号（如果为空，说明没有坐过以旧换翻新更换和回收的操作）</returns>
        public string GetBeaforOldNo(string obuNo)
        {
            //1. INTERMEDIATE_TRANSFORMATIONS 
            //2. OPERATION_LOGS
            //3. OUBNO=1.TARGET_NO
            //4. 2.OPERATION_KIND IN (189,190,191,195)
            string getInterSql = "SELECT PRIMARY_OPLOG_ID,ORIGIN_NO FROM ISSUE_RPT.dbo.INTERMEDIATE_TRANSFORMATIONS WHERE TARGET_NO=@OBUNO AND TRANSFORMATION_STATUS !=-1";
            string getLogSql = "SELECT COUNT(1) FROM ISSUE_RPT.dbo.OPERATION_LOGS WHERE ID=@ID AND RESULT=1 AND OPERATION_KIND IN (189,190,191,195,196)";

            //string sql = "SELECT A.ORIGIN_NO FROM ISSUE_RPT.dbo.INTERMEDIATE_TRANSFORMATIONS AS A INNER JOIN ISSUE_RPT.dbo.OPERATION_LOGS AS B ON A.PRIMARY_OPLOG_ID=B.ID where A.TARGET_NO=@OBUNO AND B.OPERATION_KIND IN (189,190,191,195);";
            SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("@OBUNO", SqlDbType.VarChar, 20) };
            parameters[0].Value = obuNo;
            DataTable interObj = new DatabaseHelper().ExecuteSqlDataSet(getInterSql, parameters).Tables[0];
            if (interObj != null && interObj.Rows != null && interObj.Rows.Count > 0)
            {
                SqlParameter parameterLog = new SqlParameter("ID", SqlDbType.BigInt);
                parameterLog.Value = Convert.ToInt64(interObj.Rows[0]["PRIMARY_OPLOG_ID"]);
                if (obuDB.Database.SqlQuery<int>(getLogSql, parameterLog).FirstOrDefault() > 0)
                {
                    return interObj.Rows[0]["ORIGIN_NO"].ToString();
                }
            }
            return null;
        }

        //检查日志ID对应的是否已经有Serial流水号
        public string IsAlreadySerial(long logId)
        {
            string sql = "select SERIAL_NO FROM PRINT_LOG AS A INNER JOIN PRINT_DETAIL AS B ON A.ID=B.SERIAL_ID WHERE B.LOG_ID=@LOGID AND A.STATUS=1";
            SqlParameter parameter = new SqlParameter("@LOGID", SqlDbType.BigInt);
            parameter.Value = logId;
            return obuDB.Database.SqlQuery<string>(sql, parameter).FirstOrDefault();
        }

        /// <summary>
        /// 删除维修单
        /// </summary>
        /// <param name="repairOrderId">维修单ID</param>
        /// <param name="remark">删除备注</param>
        /// <returns>删除的事务是否执行成功</returns>
        public bool DeleteRepair(int repairOrderId, string remark, string operatorNo, string agentNo, out string msg)
        {
            string procName = "PROC_DELETEREPAIR";
            DatabaseHelper dbHelper = new DatabaseHelper();
            SqlParameter[] parameters = new SqlParameter[]{
                new SqlParameter("@ID",SqlDbType.Int),
                new SqlParameter("@REMARK",SqlDbType.NVarChar,500),
                new SqlParameter("@OPERATORNO",SqlDbType.Char,6),
                new SqlParameter("@AGENTNO",SqlDbType.VarChar,16),
                new SqlParameter("@NOW_DATE",SqlDbType.VarChar,16),
                new SqlParameter("@RESULT",SqlDbType.Int)
            };
            parameters[0].Value = repairOrderId;
            parameters[1].Value = remark;
            parameters[2].Value = operatorNo;
            parameters[3].Value = agentNo;
            parameters[4].Value = DateTime.Now.ToString("yyyymmdd");
            parameters[5].Direction = ParameterDirection.Output;
            dbHelper.ExecuteProc(procName, parameters);
            msg = "";
            if (parameters[4].Value != DBNull.Value && parameters[4].Value != null && (Convert.ToInt32(parameters[4].Value) == -2))
            {
                msg = "业务日志不存在，无法删除！";
            }
            return parameters[4].Value != DBNull.Value && parameters[4].Value != null && (Convert.ToInt32(parameters[4].Value) > 0);
        }

        /// <summary>
        /// 获取当前维修单涉及到的流水中的其他维修单单号
        /// </summary>
        /// <param name="id">当前维修单ID</param>
        /// <returns>与当前维修单做同一流水的其他维修单的单号</returns>
        public string GetOtherRepair(int id)
        {
          //  string result = "";
//            string sql = @"SELECT C.OBU_NO FROM (SELECT C.LOG_ID,A.ID,C.SERIAL_ID FROM REPAIR_ORDERS AS A 
//INNER JOIN OPERATION_CARE_LOGS AS B ON A.ID=B.OPERATION_ID 
//INNER JOIN PRINT_DETAIL AS C ON B.ID=C.LOG_ID 
//INNER JOIN PRINT_LOG AS D ON C.SERIAL_ID = D.ID
//WHERE B.OPERATION_KIND=3004 and A.ID=@ID AND D.STATUS=1) AS A 
//INNER JOIN OPERATION_CARE_LOGS AS B ON A.LOG_ID=B.ID 
//INNER JOIN REPAIR_ORDERS AS C ON B.OPERATION_ID=C.ID 
//WHERE B.OPERATION_KIND =3004 AND C.STATUS=0 and A.ID<>@ID";

            string sql = @"SELECT COUNT(DISTINCT D.FUND_ID) FROM (
SELECT C.LOG_ID,A.ID,C.SERIAL_ID FROM REPAIR_ORDERS AS A 
INNER JOIN OPERATION_CARE_LOGS AS B ON A.ID=B.OPERATION_ID 
INNER JOIN PRINT_DETAIL AS C ON B.ID=C.LOG_ID 
INNER JOIN PRINT_LOG AS D ON C.SERIAL_ID = D.ID
WHERE B.OPERATION_KIND=3004 and A.ID=@ID AND D.STATUS=1) AS A
INNER JOIN PRINT_DETAIL AS B ON A.SERIAL_ID=B.SERIAL_ID
INNER JOIN OPERATION_CARE_LOGS AS C ON B.LOG_ID=C.ID
INNER JOIN FUND_DETAIL AS D ON B.SERIAL_ID=D.SERIAL_ID
WHERE C.OPERATION_KIND=3004 AND C.STATUS=1 AND C.OPERATION_ID<>@ID";
            SqlParameter parameter = new SqlParameter("@ID", SqlDbType.Int);
            parameter.Value = id;
            var fundCount = obuDB.Database.SqlQuery<int>(sql, parameter).FirstOrDefault();
            if(fundCount.ToInt()>1)
                return " 请重新提交流水单受该影响中未删除的维修单的流水。";
            //if (list != null && list.Count > 0)
            //{
            //    foreach (var item in list)
            //    {
            //        //result += item + "和";
            //        if(item.ToInt()>0)
            //    }
            //    result = result.Substring(0, result.Length - 1);
            //    return "，您当前删除的维修单与单号为" + result + "共为一个流水，请重新提交其余不删除的维修单的流水。";
            //}
            return "";
        }

        public bool DeleteParts(int id, string remark, string operatorNo, string agentNo, out string msg)
        {
            string procName = "PROC_DELETEPARTS";
            DatabaseHelper dbHelper = new DatabaseHelper();
            SqlParameter[] parameters = new SqlParameter[]{
                new SqlParameter("@ID",SqlDbType.Int),
                new SqlParameter("@REMARK",SqlDbType.NVarChar,500),
                new SqlParameter("@OPERATORNO",SqlDbType.Char,6),
                new SqlParameter("@AGENTNO",SqlDbType.VarChar,16),
                new SqlParameter("@NOW_DATE",SqlDbType.VarChar,16),
                new SqlParameter("@RESULT",SqlDbType.Int)
            };
            parameters[0].Value = id;
            parameters[1].Value = remark;
            parameters[2].Value = operatorNo;
            parameters[3].Value = agentNo;
            parameters[4].Value = DateTime.Now.ToString("yyyymmdd");
            parameters[5].Direction = ParameterDirection.Output;
            dbHelper.ExecuteProc(procName, parameters);
            msg = "";
            if (parameters[4].Value != DBNull.Value && parameters[4].Value != null && (Convert.ToInt32(parameters[4].Value) == -2))
            {
                msg = "业务日志不存在，无法删除！";
            }
            return parameters[4].Value != DBNull.Value && parameters[4].Value != null && (Convert.ToInt32(parameters[4].Value) > 0);
        }

        /// <summary>
        /// 获取当前元器件销售涉及到的流水中的其他维修单单号
        /// </summary>
        /// <param name="id">当前元器件销售ID</param>
        /// <returns>与当前维修单做同一流水的其他维修单的单号</returns>
        public string GetOtherRarts(int id)
        {
            //string result = "";
            //string sql = "select OBU_NO from PARTS_SALE where ID<>@ID AND [STATUS]=0 AND ID in(select operation_id from OPERATION_CARE_LOGS as a inner join PRINT_DETAIL as b on a.ID=b.LOG_ID where a.[STATUS]=1 and b.SERIAL_ID = (select top 1 SERIAL_ID from  PRINT_DETAIL as c inner join OPERATION_CARE_LOGS as d on c.LOG_ID = d.ID where d.OPERATION_ID=@ID and OPERATION_KIND in (3002,3003) and a.[STATUS]=1))";
//            string sql = @"SELECT C.OBU_NO FROM (
//SELECT C.LOG_ID,A.ID FROM PARTS_SALE AS A 
//INNER JOIN OPERATION_CARE_LOGS AS B ON A.ID=B.OPERATION_ID 
//INNER JOIN PRINT_DETAIL AS C ON B.ID=C.LOG_ID
//inner join PRINT_LOG AS D ON C.SERIAL_ID = D.ID 
// WHERE B.OPERATION_KIND IN (3002,3003)  AND D.STATUS=1
//and A.ID=@ID) AS A 
//INNER JOIN OPERATION_CARE_LOGS AS B ON A.LOG_ID=B.ID 
//INNER JOIN PARTS_SALE AS C ON B.OPERATION_ID=C.ID 
//WHERE B.OPERATION_KIND IN (3002,3003) AND C.STATUS=0 and A.ID<>@ID";

            string sql = @"SELECT COUNT(DISTINCT D.FUND_ID) FROM (
SELECT C.LOG_ID,A.ID,C.SERIAL_ID FROM PARTS_SALE AS A 
INNER JOIN OPERATION_CARE_LOGS AS B ON A.ID=B.OPERATION_ID 
INNER JOIN PRINT_DETAIL AS C ON B.ID=C.LOG_ID 
INNER JOIN PRINT_LOG AS D ON C.SERIAL_ID = D.ID
WHERE B.OPERATION_KIND IN (3002,3003) and A.ID=@ID AND D.STATUS=1) AS A
INNER JOIN PRINT_DETAIL AS B ON A.SERIAL_ID=B.SERIAL_ID
INNER JOIN OPERATION_CARE_LOGS AS C ON B.LOG_ID=C.ID
INNER JOIN FUND_DETAIL AS D ON B.SERIAL_ID=D.SERIAL_ID
WHERE C.OPERATION_KIND IN (3002,3003) AND C.STATUS=1 AND C.OPERATION_ID<>@ID";

            SqlParameter parameter = new SqlParameter("@ID", SqlDbType.Int);
            parameter.Value = id;
            var fundCount = obuDB.Database.SqlQuery<int>(sql, parameter).FirstOrDefault();
            if (fundCount.ToInt() > 1)
                return " 请重新提交未受删除影响的剩余元器件销售的流水。";
            //if (list != null && list.Count > 0)
            //{
            //    foreach (var item in list)
            //    {
            //        result += item + "和";
            //    }
            //    result = result.Substring(0, result.Length - 1);
            //    return "，您当前删除的元器件销售信息与标签号为：" + result + "共为一个流水，请重新提交其余不删除的标签的流水。";
            //}
            return "";
        }

        #region 查询当前业务涉及到的其他的发票信息
        public bool GetOtherInvoice(long logId)
        {
            string sql = @"select COUNT(distinct a.SERIAL_ID) from INVOICE_DETAIL as a
    inner join ( select distinct d.INVOICE_ID from OPERATION_CARE_LOGS as a 
	inner join PRINT_DETAIL as c on c.LOG_ID=a.ID
	inner join PRINT_LOG AS E on c.SERIAL_ID = E.ID
	inner join INVOICE_DETAIL as d on d.SERIAL_ID=c.SERIAL_ID
	INNER JOIN INVOICE_INFO AS F ON D.INVOICE_ID = F.ID 
	where  e.STATUS=1 AND F.STATUS=1 and a.id=@LOG_ID) as b  on a.INVOICE_ID=b.INVOICE_ID 
	inner join PRINT_LOG as c on a.SERIAL_ID=c.ID 
	where c.STATUS=1";
            SqlParameter parameter = new SqlParameter("@LOG_ID", SqlDbType.BigInt);
            parameter.Value = logId;
            return obuDB.Database.SqlQuery<int>(sql, parameter).FirstOrDefault() > 1;

        }
        #endregion

        public long GetOperationIdByRepairId(long id)
        {
            return (from o in obuDB.OPERATION_CARE_LOGS
                    where o.OPERATION_ID == id && (o.OPERATION_KIND == 3001 || o.OPERATION_KIND == 3004 || o.OPERATION_KIND == 3005)
                    select o.ID).FirstOrDefault();
        }

        public long GetOpertionIdByPartsId(long id)
        {
            return (from o in obuDB.OPERATION_CARE_LOGS
                    where o.OPERATION_ID == id && (o.OPERATION_KIND == 3002 || o.OPERATION_KIND == 3003)
                    select o.ID).FirstOrDefault();
        }

        /// <summary>
        /// 获取一口价费用
        /// </summary>
        /// <returns></returns>
        public decimal GetOneRepairPay()
        {
            string sql = "SELECT TOP 1 PRICE FROM SPECIAL_REPAIR_FEE ORDER BY START_DATE DESC";
            return obuDB.Database.SqlQuery<decimal>(sql).FirstOrDefault();
        }
        /// <summary>
        /// 获取一口价厂商报价
        /// </summary>
        /// <returns></returns>
        public decimal GetOneRepairPaySup()
        {
            string sql = "SELECT TOP 1 SUPPLIER_PRICE FROM SPECIAL_REPAIR_FEE ORDER BY START_DATE DESC";
            return obuDB.Database.SqlQuery<decimal>(sql).FirstOrDefault();
        }

        /// <summary>
        /// 查询标签号是否有一口价维修的历史
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public DateTime? GetOneRepairHistory(string p)
        {
            string sql = "select MAX(REPORT_DATE) FROM REPAIR_ORDERS WHERE ORDER_TYPE=2 AND STATUS=17 AND OBU_NO='" + p + "'";
            return obuDB.Database.SqlQuery<DateTime?>(sql).FirstOrDefault();
        }
    }
}
